package eu.gegenleitner.esspacc.gui;

import java.security.cert.X509Certificate;

import eu.gegenleitner.esspacc.xmlSignature.XMLSignatureRequester;
import eu.gegenleitner.esspacc.xmlSignature.XMLSignatureVerifier;

public class RunnableAutoFillInUserName implements Runnable {
	
	private MainWindow mainwindow;
	
	public RunnableAutoFillInUserName(MainWindow window) {
		this.mainwindow = window;
	}

	@Override
	public void run() {
		mainwindow.addLineToUserInfo("Getting Usernames from BKU\t\t\t", true);
		XMLSignatureRequester req = new XMLSignatureRequester();
		XMLSignatureVerifier veri = new XMLSignatureVerifier();
//		String xmlSignature = req.getXMLSignature();
		String xmlSignature = req.getXMLSignature("Please Sign this document to fill in your names!");
		if( veri.isXMLSignatureValid(xmlSignature) ) {
			X509Certificate cert = veri.getCertificateFromXMLSignature(xmlSignature);
			String[] subjectAttributes = cert.getSubjectDN().getName().split(", ");
			String givenName = subjectAttributes[1].replaceFirst("GIVENNAME=", "");
			String surName = subjectAttributes[2].replaceFirst("SURNAME=", "");
			mainwindow.getGNameTextField().setText(givenName);
			mainwindow.getSNameTextField().setText(surName);
			mainwindow.addLineToUserInfo("[DONE]", false);
		} else {
			mainwindow.addLineToUserInfo("[ERROR] Bad XMLSignature!", true);
		}
		
	}

}
